package com.fit.pages;

import java.util.Date;

import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.ioc.annotations.Inject;

import com.fit.annotations.AdminAccess;
import com.fit.annotations.AnonymousAccess;
import com.fit.annotations.ProfessorAccess;
import com.fit.annotations.StudentAccess;
import com.fit.dao.user.UserDAO;
import com.fit.entities.user.User;
import com.fit.model.MD5;
import com.fit.services.Authenticator;

@AdminAccess
@ProfessorAccess
@StudentAccess
public class Index
{
	@Inject
	private Authenticator authenticator;
	@Property
	private User user;
	
	@Property
	private String newPassword;
	

	@Property
	private String newPassword2;
	
	@Inject
	private UserDAO userDAO;
	
	public User getLoggedUser() {
//		if (authenticator.isLoggedIn()) {
			return authenticator.getLoggedUser();
//		}
//		return null;
	}	

	@InjectPage
	private ErrorPage errorPage;
	
	@Component
	private Form changeForm;
	
	Object onSuccessFromChangeForm() {
		System.out.println("kako jeee"+getLoggedUser().getId());
		user = userDAO.findByID(getLoggedUser().getId());
		try {
			if (newPassword != null) {
				System.out.println("1");
				if(newPassword.equalsIgnoreCase(newPassword2)){
					System.out.println("2");
					newPassword = MD5.md5(newPassword);
					user.setPassword(newPassword);
					System.out.println("3");
					System.out.println(newPassword + newPassword2);
					getLoggedUser().setPassword(newPassword);
					userDAO.update(user);
					
					System.out.println("PASSWORD POSLE UPDATEA" + getLoggedUser().getPassword());
					return Index.class;
					
//				if (newPassword.equals(user.getPassword())) {
//						System.out.println("4");
//						user.setPassword(newPassword);
//						System.out.println("5");
//					}
				}
				
			}
			System.out.println("4");
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			errorPage.setMessage("Error! ");
			return errorPage;
		}

	}
	
	

	public Date getCurrentTime() 
	{ 
		return new Date(); 
	}
	
	public String name(){
		return "Hello FIT!";
	}
	
	public Object onActionFromLogout() {
		authenticator.logout();
		return Index.class;
	}
	
}
